package org.jeecgframework.web.tcdev.controller;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.tcdev.entity.TArticle;
import org.jeecgframework.web.tcdev.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 文章管理控制层
 * Created by zjy on 2015/4/13.
 */
@Scope("prototype")
@Controller
@RequestMapping("/articleController")
public class ArticleController extends BaseController {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(ArticleController.class);

    @Autowired
    private ArticleService articleService;

    @Autowired
    private SystemService systemService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    @RequestMapping(params = "article")
    public ModelAndView article(HttpServletRequest request) {

        return new ModelAndView("tcdev/article/articleList");
    }



    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(TArticle article, HttpServletRequest request,
                         HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(TArticle.class, dataGrid);


        cq.add();

        // 查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, article, request.getParameterMap());
        this.articleService.getDataGridReturn(cq, true);

        List dataList = dataGrid.getResults();

        String sql = "select t3.title from t_article_has_category t1\n" +
                "left join t_article t2 on t1.article_id = t2.id\n" +
                "left join t_article_category t3 on t1.article_category_id = t3.id\n" +
                "where t1.article_id = ";

        for(Object obj : dataList){

            TArticle temp = (TArticle) obj;

            List<String> acList = articleService.findListbySql(sql + temp.getId());

            if(acList != null && acList.size() > 0){

                temp.setArticleCateGoryName(StringUtil.joinString(acList,","));

            }

        }


        TagUtil.datagrid(response, dataGrid);
    }




    /**
     * 跳转到顾客基础信息页面
     *
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(TArticle article,
                                    HttpServletRequest req) {


        List<String> articleCategoryList = null;
        if (StringUtil.isNotEmpty(article.getId())) {
            article = articleService.getEntity(TArticle.class, article.getId());

            req.setAttribute("article", article);

            articleCategoryList = articleService.findListbySql("select article_category_id from t_article_has_category where article_id=" + article.getId());

        }

        if(articleCategoryList != null ){
            req.setAttribute("articleCategoryList", JSON.toJSON(articleCategoryList));
        }else{
            req.setAttribute("articleCategoryList", "[]");
        }


        return new ModelAndView("tcdev/article/article");
    }


    /**
     * 添加文章信息
     *
     * @param article
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(TArticle article, HttpServletRequest request) {

        AjaxJson j = new AjaxJson();
        if (StringUtil.isNotEmpty(article.getId())) {
            message = MutiLangUtil.paramUpdSuccess("文章");

            try {
                String articleCategoryIdStr = request.getParameter("articleCategoryIds");

                String[] articleCategoryIds = articleCategoryIdStr.split(",");

                articleService.updateArticleAndHasCategory(article,articleCategoryIds);

            } catch (Exception e) {
                e.printStackTrace();
                message = MutiLangUtil.paramUpdFail("文章");
            }
        } else {
            if(StringUtil.isEmpty(message))
            {

//                TSUser user = ResourceUtil.getSessionUserName();


                String articleCategoryIdStr = request.getParameter("articleCategoryIds");

                String[] articleCategoryIds = articleCategoryIdStr.split(",");

                try {
                    articleService.addArticleAndHasCategory(article, articleCategoryIds);

                    message = MutiLangUtil.paramAddSuccess("文章");
                } catch (Exception e) {
                    e.printStackTrace();

                    message = "保存文章失败";
                }



            }
        }
        systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }


    /**
     * 删除文章 物理删除
     *
     * @return
     */
    @RequestMapping(params = "delArticle")
    @ResponseBody
    public AjaxJson delArticle(TArticle article, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        article = articleService.getEntity(TArticle.class, article.getId());


        try {

            articleService.deleteArticleAndHasCategory(article);

            message = "文章: " + article.getTitle() + "被删除成功";

        } catch (Exception e) {
            e.printStackTrace();

            message = "文章: " + article.getTitle() + "删除失败";
        }
        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }


    /**
     * 预览文章
     *
     * @param id
     * @return
     */
    @RequestMapping(params = "preview")
    public ModelAndView preview(String id, HttpServletRequest req) {

        TArticle article = articleService.getEntity(TArticle.class, id);

        req.setAttribute("article", article);

        return new ModelAndView("tcdev/article/preview");
    }

    /**
     * 发布文章
     *
     * @param id
     * @return
     */
    @RequestMapping(params = "publish")
    @ResponseBody
    public AjaxJson publish(String id, HttpServletRequest req) {

        AjaxJson j = new AjaxJson();

        TArticle article = articleService.getEntity(TArticle.class, id);

        if("1".equals(article.getIsPublish())){
            message = "当前文章已经被发布了，不能重复发布！";
        }else{

            article.setIsPublish("1");
            article.setPublishTime(new Date());
            articleService.saveOrUpdate(article);

            message = "发布【"+article.getTitle()+"】成功";
        }

        j.setMsg(message);
        return j;
    }


}
